import pymysql


class DbUtil:
    conn =None
    #封装建立连接的方法
    @classmethod
    def connect(cls):
        cls.conn=pymysql.Connect(host="211.103.136.244",port=7061,user="student",
                            password="iHRM_student_2022",database="ihrm",charset="utf8")
        return cls.conn
    #封装关闭连接的方法
    @classmethod
    def conn_close(cls):
        cls.conn.close()
    #封装查询数据库的方法
    @classmethod
    def query(cls,sql):
        cursor = None
        result =None
        try:
            cls.conn =cls.connect()
            cursor =cls.conn.cursor()
            cursor.execute(sql)
            result =cursor.fetchone()
        except Exception as err:
            print('查询数据时报错',str(err))
        finally:
            cursor.close()
            cls.conn_close()
            return result
    #封装增删改数据库的方法
    @classmethod
    def uid(cls,sql):
        cursor =None
        try:
            cls.conn =cls.connect()
            cursor =cls.conn.cursor()
            cursor.execute(sql)
            affect_rows =cls.conn.affected_rows()
            cls.conn.commit()
        except Exception as err:
            print('增删改数据库时报错',str(err))
            cls.conn.rollback()
        finally:
            cursor.close()
            cls.conn_close()

